package com.example.springbootrbac.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.springbootrbac.entity.UserEntity;
import com.example.springbootrbac.pojo.Result;
import com.example.springbootrbac.pojo.ResultCode;
import com.example.springbootrbac.repository.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    ObjectMapper objectMapper;
    @Resource(name = "userRepository")
    UserRepository userRepository;

    //登录成功处理器
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        HttpSession session = httpServletRequest.getSession();
        Object ifUser = session.getAttribute("user");
        if (ObjectUtils.isNotEmpty(ifUser)) {//判断是否重复登录
            httpServletResponse
                    .getWriter()
                    .write(objectMapper.writeValueAsString(Result.failure(ResultCode.FAILURE_REPEAT_LOGIN_ERROR)));
        } else {
            String token = authentication.getName();
            httpServletResponse
                    .getWriter()
                    .write(objectMapper.writeValueAsString(Result.success("登录成功,欢迎" + authentication.getName() + "到来~", token)));

            UserEntity user = userRepository.selectOne(
                    new QueryWrapper<UserEntity>()
                            .select("id", "username", "password", "identity", "status")
                            .eq("username", authentication.getName())
            );
            session.setAttribute("user", user);
        }

    }
}
